/** Essential APIs for working with BaseRequestUtils. */
@file:JvmMultifileClass
@file:JvmName("BaseRequestUtils")

package hos.net.soap.extension

import com.drake.net.NetConfig
import com.drake.net.request.BaseRequest
import com.drake.net.response.convert
import hos.net.http.reflect.TypeUtil
import java.lang.reflect.Type

/**
 * <p>Title: BaseRequestExt </p>
 * <p>Description:  </p>
 * <p>Company: www.mapuni.com </p>
 *
 * @author : 蔡俊峰
 * @date : 2024-04-09 14:10
 * @version : 1.0
 */
/**
 * 执行同步请求
 * 本方法仅为兼容Java使用存在
 * @param rawType
 * @param typeArguments
 */
fun <R> BaseRequest.execute(rawType: Type, vararg typeArguments: Type): R {
    if (typeArguments.isEmpty()) {
        return execute(rawType);
    }
    val type = TypeUtil.typeOf(rawType, *typeArguments)
    NetConfig.requestInterceptor?.interceptor(this)
    val request = buildRequest()
    val newCall = okHttpClient.newCall(request)
    return newCall.execute().convert(type)
}

/**
 * 执行同步请求
 * @return 一个包含请求成功和错误的Result
 */
fun <R> BaseRequest.toResult(rawType: Type, vararg typeArguments: Type): Result<R> {
    if (typeArguments.isEmpty()) {
        return toResult(rawType);
    }
    val type = TypeUtil.typeOf(rawType, *typeArguments)
    NetConfig.requestInterceptor?.interceptor(this)
    val request = buildRequest()
    val newCall = okHttpClient.newCall(request)
    return try {
        val value = newCall.execute().convert<R>(type)
        Result.success(value)
    } catch (e: Exception) {
        Result.failure(e)
    }
}

/**
 * 执行同步请求
 * @return 一个包含请求成功和错误的Result
 */
fun <R> BaseRequest.toResult(type: Type): Result<R> {
    NetConfig.requestInterceptor?.interceptor(this)
    val request = buildRequest()
    val newCall = okHttpClient.newCall(request)
    return try {
        val value = newCall.execute().convert<R>(type)
        Result.success(value)
    } catch (e: Exception) {
        Result.failure(e)
    }
}

